import { WebSocketGateway, WebSocketServer } from "@nestjs/websockets";
import { Socket, Server } from "socket.io";
import { SongService } from "src/song/song.service";
import { decrypt, getTimeStamp, queryString } from "src/utils/common";
import { CacheRedisService } from "src/cache-redis/cache-redis.service";

@WebSocketGateway({
  allowEIO3: true,
  cors: {
    origin: "*",
    credentials: true,
  },
  transports: ["websocket"],
})
export class WsGateway {
  constructor(private song: SongService, private redis: CacheRedisService) {
    setInterval(async () => {
      const res = await song.execute();
      //如果接收到的值是空，那么就不会广播
      for (let i = 0; i < res.length; i++) {
        this.server.to(res[i].room_id.toString()).emit("playSong", {
          song: res[i].song,
          sysTime: getTimeStamp(),
        });
      }
    }, 6000);
  }

  @WebSocketServer()
  server: Server;

  async send(room_id: string, data: any) {
    this.server.to(room_id).emit("text", data);
  }
  async handleConnection(client: Socket, ...args: any[]) {
    const str = decrypt(client.handshake.query.tick as string);
    const obj = queryString(str) as any;
    if (obj.timeStamp) {
      if (getTimeStamp() > Number(obj.timeStamp) + 300) {
        client.disconnect();
      } else {
        client.join(obj.room_id as any);
        const res = await this.song.getNowPlayingSong(obj.room_id);
        if (res) {
          client.emit("playSong", { sysTime: getTimeStamp(), song: res });
        }
      }
    }
  }
}
